package com.daleige.common;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class NetUtil {
	/**
	 * 获取本地ip地址
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getLocalIp() throws Exception {
		return getIp(getLocalInetAddress());
	}
	
	/**
	 * 获取ip地址
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getIp(InetAddress inetAddress) throws Exception {
		return inetAddress.getHostAddress();
	}

	/**
	 * 获取本地计算机名称
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String getLocalName() throws Exception {
		return getLocalInetAddress().getHostName();
	}
	
	public static InetAddress getLocalInetAddress() throws Exception {
		return InetAddress.getLocalHost();
	}
	
	public static InetAddress[] getLocalInetAddresss() throws Exception {
		return InetAddress.getAllByName(getLocalName());
	}
	
	/**
     * 测试本机端口是否被使用
     * @param port
     * @return
     */
    public static boolean isLocalPortUsing(int port){  
        boolean flag = true;  
        try {
            //如果该端口还在使用则返回true,否则返回false,127.0.0.1代表本机
            flag = isPortUsing("127.0.0.1", port);  
        } catch (Exception e) {  
        }  
        return flag;  
    }  
    /*** 
     * 测试主机Host的port端口是否被使用
     * @param host 
     * @param port 
     * @throws UnknownHostException  
     */  
    public static boolean isPortUsing(String host,int port) throws UnknownHostException{  
        boolean flag = false;  
        InetAddress Address = InetAddress.getByName(host);  
        try {  
            Socket socket = new Socket(Address,port);  //建立一个Socket连接
            socket.close();
            flag = true;  
        } catch (IOException e) {  

        }  
        return flag;  
    }  
}
